import 'dart:async';
import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/api/odoo/product_template_odoo_api.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';

import 'package:syncfusion_flutter_core/theme.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

final textStyle = TextStyle(
  color: Color.fromRGBO(255, 255, 255, 1),
  fontSize: 18.sp,
  decoration: TextDecoration.none,
);

class ProductionMonitoring extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _BulletinBoard();
}

class _BulletinBoard extends State<ProductionMonitoring> {

  late DataSource _dataSource = DataSource([]);
  final DataGridController _controller = DataGridController();
  final ScrollController _verticalScrollController = ScrollController();
  late Timer timer;
  double _currentRow = 0;
  @override
  Widget build(BuildContext context) {
    return _buildDataGrid();
  }

  @override
  void initState() {
    super.initState();
    _loadData();
    timer = Timer.periodic(Duration(seconds: 3), (Timer t) => autoScroll());
  }

  @override
  void dispose() {
    timer.cancel();
    super.dispose();
  }

  _loadData() async {
    ResponseBodyApi responseBodyApi =
        await ProductTemplateOdooApi.ProductionMonitoring();
    if (responseBodyApi.success!) {
      List data = responseBodyApi.data;
      _dataSource = DataSource(data);
      setState(() {});
    }
  }

  autoScroll(){
    if (_verticalScrollController.position.pixels ==
        _verticalScrollController.position.maxScrollExtent) {
      _currentRow = 0;
    }else{
      _currentRow += 300;
    }
    _controller.scrollToCell(_currentRow, 1,canAnimate:true);
  }

  _buildDataGrid() {
    return Container(
      decoration: BoxDecoration(

          //背景图片
          image: DecorationImage(
        //图片地址
        image: AssetImage(
          'assets/bg/bg7.jpg',
        ),
        fit: BoxFit.cover,
        //背景图片位置，相当于css中的background-position
      )),
      child: Column(
        children: [
          Container(
            // width: width,
            alignment: Alignment.center,
            color: Color.fromRGBO(48, 48, 85, 1.0),
            child: Padding(
              padding: EdgeInsets.all(10),
              child: Text(
                "数字化工厂管理系统",
                style: TextStyle(
                    color: Color.fromRGBO(255, 255, 255, 1),
                    decoration: TextDecoration.none,
                    fontSize: 25.sp),
              ),
            ),
          ),
          Expanded(
            child: SfDataGridTheme(
              data: SfDataGridThemeData(
                  headerHoverColor: Colors.transparent,
                  sortIconColor: Colors.white,
                  headerColor:
                      Colors.black, //Color.fromRGBO(13, 152, 110, 0.95),
                  gridLineColor: Color.fromRGBO(0, 0, 0, 1.0)),
              child: SfDataGrid(
                controller: _controller,
                verticalScrollController: _verticalScrollController,
                columnWidthMode: ColumnWidthMode.fill,
                columnWidthCalculationRange:
                    ColumnWidthCalculationRange.allRows,
                allowSorting: true, //是否开启排序
                allowMultiColumnSorting: true, //排序顺序
                allowTriStateSorting: true, //三态排序
                // frozenColumnsCount: 1,
                rowHeight: 55.h,
                headerRowHeight: 55.h,
                source: _dataSource,
                gridLinesVisibility: GridLinesVisibility.both,
                headerGridLinesVisibility: GridLinesVisibility.both,
                columns: [
                  GridColumn(
                      columnName: '序号',
                      maximumWidth: 100.r,
                      label: Container(
                          padding: EdgeInsets.symmetric(horizontal: 16.0),
                          alignment: Alignment.center,
                          child: Text(
                            '序号',
                            style: textStyle,
                            overflow: TextOverflow.ellipsis,
                          ))),
                  GridColumn(
                      columnName: '生产单号',
                      label: Container(
                          padding: EdgeInsets.symmetric(horizontal: 16.0),
                          alignment: Alignment.center,
                          child: Text(
                            '生产单号',
                            style: textStyle,
                            overflow: TextOverflow.ellipsis,
                          ))),
                  GridColumn(
                      columnName: '零件图号',
                      label: Container(
                          padding: EdgeInsets.symmetric(horizontal: 16.0),
                          alignment: Alignment.center,
                          child: Text(
                            '零件图号',
                            style: textStyle,
                            overflow: TextOverflow.ellipsis,
                          ))),
                  GridColumn(
                      columnName: '零件名称',
                      label: Container(
                          padding: EdgeInsets.symmetric(horizontal: 16.0),
                          alignment: Alignment.center,
                          child: Text(
                            '零件名称',
                            style: textStyle,
                            overflow: TextOverflow.ellipsis,
                          ))),
                  GridColumn(
                      columnName: '规格型号',
                      label: Container(
                          padding: EdgeInsets.symmetric(horizontal: 16.0),
                          alignment: Alignment.center,
                          child: Text(
                            '规格型号',
                            style: textStyle,
                            overflow: TextOverflow.ellipsis,
                          ))),
                  GridColumn(
                      columnName: '计划数量',
                      maximumWidth: 130.r,
                      label: Container(
                          padding: EdgeInsets.symmetric(horizontal: 16.0),
                          alignment: Alignment.center,
                          child: Text(
                            '计划数量',
                            style: textStyle,
                            overflow: TextOverflow.ellipsis,
                          ))),
                  GridColumn(
                      columnName: '报工数量',
                      maximumWidth: 130.r,
                      label: Container(
                          padding: EdgeInsets.symmetric(horizontal: 16.0),
                          alignment: Alignment.center,
                          child: Text(
                            '报工数量',
                            style: textStyle,
                            overflow: TextOverflow.ellipsis,
                          ))),
                  GridColumn(
                      columnName: '完成率',
                      maximumWidth: 150.r,
                      label: Container(
                          padding: EdgeInsets.symmetric(horizontal: 16.0),
                          alignment: Alignment.center,
                          child: Text(
                            '完成率',
                            style: textStyle,
                            overflow: TextOverflow.ellipsis,
                          ))),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}

BoxDecoration drawBorder() {
  final borderSide =
      BorderSide(width: 1.0, color: const Color.fromRGBO(0, 0, 0, 1.0));
  return BoxDecoration(
      border: Border(
          left: borderSide,
          right: borderSide,
          bottom: borderSide,
          top: borderSide));
}

class DataSource extends DataGridSource {
  DataSource(List list) {
    int index = 1;
    dataGridRows = list
        .map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
              DataGridCell<num>(columnName: '序号', value: index++),
              DataGridCell<String>(
                  columnName: '生产单号', value: dataGridRow["productionorderno"]),
              DataGridCell<String>(columnName: '零件图号', value: dataGridRow["product_id"]["default_code"]),
              DataGridCell<String>(columnName: '零件名称', value: dataGridRow["product_id"]["name"]),
              DataGridCell<String>(columnName: '规格型号', value: dataGridRow["product_id"]["description"]),
              DataGridCell<num>(columnName: '计划数量', value: dataGridRow["planned_quantity"]),
              DataGridCell<num>(columnName: '报工数量', value: dataGridRow["qualifiedquantity"]),
              DataGridCell<num>(columnName: '完成率', value: dataGridRow["percentage_complete"]),
            ]))
        .toList();
  }

  List<DataGridRow> dataGridRows = [];

  @override
  List<DataGridRow> get rows => dataGridRows;
  Widget buildSoftwareProficiency(dynamic value) {
    Widget getLinearProgressBar(num progressValue) {
      return Container(
        width: 120.r,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Container(
              height: 22.r,
              width: 80.r,
              child: ClipRRect(
                  // 边界半径（`borderRadius`）属性，圆角的边界半径。
                  borderRadius: BorderRadius.all(Radius.circular(10.0)),
                  child: LinearProgressIndicator(
                    value: progressValue / 100,
                    valueColor: AlwaysStoppedAnimation<Color>(progressValue < 50
                        ? Colors.red
                        : progressValue < 70
                            ? Colors.yellow
                            : Colors.green),
                    backgroundColor: progressValue < 50
                        ? Colors.red[100]
                        : Colors.green[100],
                  )),
            ),
            Text(
              ' ' + (progressValue.toString() + '%'),
              style: TextStyle(
                  color: Colors.red, //Color.fromRGBO(255, 255, 255, 1),
                  decoration: TextDecoration.none,
                  fontSize: 20.sp),
            ),
          ],
        ),
      );
    }

    return getLinearProgressBar(value * 100);
  }

  @override
  DataGridRowAdapter? buildRow(DataGridRow row) {
    Color getRowBackgroundColor() {
      final int index = dataGridRows.indexOf(row);
      if (index % 2 != 0) {
        return Color.fromRGBO(137, 143, 217, 0.8);
      }
      // 157,156,190
      return Color.fromRGBO(157, 156, 190, 0.9);
    }

    return DataGridRowAdapter(
        color: getRowBackgroundColor(),
        cells: row.getCells().map<Widget>((dataGridCell) {
          Color getColor() {
            if (dataGridCell.columnName == '生产状态') {
              if (dataGridCell.value == '生产中') {
                return Colors.green;
              } else if (dataGridCell.value == '待生产') {
                return Colors.yellow[200]!;
              } else if (dataGridCell.value == '停机') {
                return Colors.redAccent[200]!;
              }
            }

            return Colors.transparent;
          }

          return dataGridCell.columnName == '完成率'
              ? buildSoftwareProficiency(dataGridCell.value)
              : Container(
                  alignment: Alignment.center,
                  padding: EdgeInsets.symmetric(horizontal: 16.0),
                  child: Text(
                    dataGridCell.value.toString(),
                    style: TextStyle(
                      color: Color.fromRGBO(0, 0, 0, 1.0),
                      fontSize: 18.sp,
                    ),
                    overflow: TextOverflow.ellipsis,
                  ));
        }).toList());
  }
}
